<!--
 * @FilePath: /my-map-demo/src/views/layer-management/layer-change/index.vue
 * @Author: 张文鑫
 * @Date: 2024-11-30 23:24:18
 * @Description: 
-->
<template>
  <div class="map-container">
    <div class="map-tool">
      <el-button class="map-tool-item" @click="changeBaseMap(1)">影像图层</el-button>
      <el-button class="map-tool-item" @click="changeBaseMap(2)">矢量图层</el-button>
      <el-button class="map-tool-item" @click="changeBaseMap(3)">地形图层</el-button>
    </div>
    <div class="map-content">
      <div id="map"></div>
    </div>
  </div>
</template>

<script setup>
import "ol/ol.css";
import { Map, View } from "ol";
import { defaults as defaultControls, ScaleLine } from "ol/control";
import { defaults as defaultInteractions } from "ol/interaction";
import { onMounted, onBeforeUnmount } from "vue";
import { cityNameLayer, img_wLayer, vec_wLayer, ter_wLayer } from "../common/map-config";

let map;
let layers = [img_wLayer, vec_wLayer, ter_wLayer]; // 其他图层
let allLayers = [img_wLayer, vec_wLayer, ter_wLayer, cityNameLayer]; // 所有图层（包括城市名称图层）
const initMap = () => {
  try {
    map = new Map({
      target: "map",
      controls: defaultControls({
        attribution: false,
        zoom: false,
        rotate: false,
      }),
      view: new View({
        center: [119.9319, 30.6554],
        zoom: 8,
        projection: "EPSG:4326",
      }),
      interactions: defaultInteractions({
        doubleClickZoom: false,
      }),
      layers: allLayers,
    });

    // 添加比例尺控制
    const scaleLineControl = new ScaleLine();
    map.addControl(scaleLineControl);
  } catch (error) {
    console.log("初始化地图失败", error);
  }
};

const changeBaseMap = (layerIndex) => {
  // 如果你有多个图层可以切换，这里实现切换逻辑
  // 切换图层
  layers.forEach((layer, index) => {
    layer.setVisible(index === layerIndex - 1);
  });
};

onMounted(() => {
  initMap();
});

onBeforeUnmount(() => {
  if (map) {
    map.setTarget(null); // 销毁地图实例
  }
});
</script>

<style lang="scss" scoped>
.map-container {
  position: relative;
  width: 100%;
  .map-content {
    z-index: 0;
    #map {
      height: 90vh;
      z-index: 1;
      border: none;
      cursor: move;
      background: #000;
    }
  }

  .map-tool {
    position: absolute;
    top: 10px;
    right: 10px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    background: rgba(255, 255, 255, 0.8);
    padding: 8px;
    border-radius: 8px;
    box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
    z-index: 10; /* 保证工具栏的按钮在地图上层 */
  }

  .map-tool-item {
    background-color: #007bff;
    color: white;
    border: none;
    padding: 6px 12px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    margin: 0;
    transition: background-color 0.3s;
    &:hover {
      background-color: #0056b3;
    }
  }
}
</style>
